import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { EventProvider } from '../../providers/event/event';
/**
 * Generated class for the Login page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
	selector: 'page-login',
	templateUrl: 'login.html',
})
export class LoginPage {

	//必须静态常量来传递
	private static thatPage: any;

	public loginInfo = {
		UserName: '',
		PassWord: '',
		Remember: true
	};

	constructor(
		public navCtrl: NavController,
		public navParams: NavParams,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public event: EventProvider) {

	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad LoginPage');
		LoginPage.thatPage = this;
		//绑定事件
		this.event.bindEvents(this.event.EVENT_LOGIN, this.eventPage);
		//刷新数据
		this.event.sendEvents(this.event.EVENT_LOGIN, {});
		//最近一次登录账户显示
		this.storage.getStorage("user").then(val => {
			if (val != undefined) {
				this.loginInfo.UserName = val['username'];
				this.loginInfo.PassWord = val['password'];
			}
		});
	}

	/*界面销毁*/
	ionViewWillUnload() {
		this.event.unbindEvents(this.event.EVENT_LOGIN, this.eventPage);
	}

	/*侦听事件 */
	eventPage(val: any) {
		//刷新数据
		LoginPage.thatPage.checkLogin();
	}

	/*检查登录*/
	checkLogin() {
		this.storage.getStorage("user").then(val => {
			if (val == undefined) {
				this.navCtrl.popToRoot(); //显示登录
			} else {
				this.navCtrl.push("TabsPage"); //登录成功
			}
		});
	}

	/*登录操作*/
	loginOnSuccess() {
		//正式
		if (this.inputCheck()) {
			//请求方式如下
			let params = {
				username: this.loginInfo.UserName,
				password: this.loginInfo.PassWord
			};
			this.http.postJson('user', 'dologin.do', params).then(res => {
				if (res['success'] == true) {
					//登录成功
					this.storage.saveStorage("user", {
						"user_id": res['data']['user_id']
					}).then(success => {
						//刷新当前数据
						this.event.sendEvents(this.event.EVENT_LOGIN, {});
					});
					//保存上次登录信息
					if (this.loginInfo.Remember)
						this.storage.saveStorage('last_login', params);
				} else {
					this.dialog.showAlert("提示", res['msg']);
				}
			});
		}
	}

	/*找回密码*/
	loginFindPass() {
		this.navCtrl.push("FindpassPage");
	}

	/*登录校验*/
	inputCheck() {
		if (this.loginInfo.UserName == "") {
			this.dialog.showAlert("提示", "请输入用户名");
			return false;
		}
		if (this.loginInfo.PassWord == "") {
			this.dialog.showAlert("提示", "请输入密码");
			return false;
		}
		return true;
	}
}